package com.cong.security.core.code;

import java.io.IOException;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.cong.security.core.code.image.ImageCode;
import com.cong.security.core.code.sms.SmsCodeSender;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletWebRequest;

/**
 * 验证码接口，图形验证码，短信验证码之类
 *
 * @author single-聪
 */
@Slf4j
@RestController
@RequestMapping("code")
public class CodeController {

    public static String SESSION_KEY = "SESSION_KEY_IMAGE_CODE";

    // 生成验证码接口
    @Autowired
    private ValidateCodeGenerator imageCodeGenerator;

    private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();

    /**
     * @return void
     * @Description 图形验证码生成
     * @Param [request, response]
     * @Author single-聪
     * @Date 20:12 2020/1/10
     * @Version 1.0.1
     **/
    @RequestMapping(value = "image")
    public void createCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 强转成imageCode
        ImageCode imageCode = (ImageCode) imageCodeGenerator.generate();
        sessionStrategy.setAttribute(new ServletWebRequest(request), SESSION_KEY, imageCode);
        // 图片写入IO响应中
        ImageIO.write(imageCode.getBufferImage(), "JPEG", response.getOutputStream());
    }

    // 短信验证码接口
    @Autowired
    private ValidateCodeGenerator smsCodeGenerator;
    // 发送短信接口
    @Autowired
    private SmsCodeSender smsCodeSender;

    /**
     * 用户短信登录接口
     *
     * @param mobile 手机号
     * @param type   类型
     * @author single-聪
     * @date 2019年10月16日
     * @version 1.0.1
     */
    @RequestMapping(value = "sms", method = RequestMethod.POST, consumes = "application/json;charset=UTF-8")
    public void sms(@RequestBody String c) {
        JSONObject strj = (JSONObject) JSONObject.parseObject(c);
        String mobile = strj.getString("mobile");
        String type = strj.getString("type");
        ValidateCode smsCode = smsCodeGenerator.generate();
        log.info("向手机号:[{}]发送[{}]类型短信验证码为[{}]", mobile, type, smsCode.getCode());
        // 放到redis缓存中，设置过期时间(分类型存储)
        smsCodeSender.send(type, mobile, smsCode.getCode());
    }
}
